var url = require('url');
var crypto = require('crypto');
var formstream = require('formstream');
var common   = require( '../../cloud/common' );
var querystring = require('querystring');
var rpc = require('../../cloud/qiniu/rpc');
var fop = require('../../cloud/qiniu/fop');
var conf = require('../../cloud/qiniu/conf');
var util = require('../../cloud/qiniu/util');
var Mac = require('../../cloud/qiniu/auth/digest').Mac;
var picType=new Array("gif","jpg","jpeg","png","bmp","x-png");
var audioType=new Array("3gp","wma","wav","mp3","mp4","afc","ogg","rm","ape","voc","aac");
var vedioType=new Array("avi","asf","wmv","avs","flv","mkv","mov","3gp","mp4","mpeg","rm","rmvb","flash");
exports.Client = Client;
exports.Entry = Entry;
exports.EntryPath = EntryPath;
exports.EntryPathPair = EntryPathPair;
exports.BatchItemRet = BatchItemRet;
exports.BatchStatItemRet = BatchStatItemRet;
exports.PutPolicy = PutPolicy;
exports.GetPolicy = GetPolicy;
exports.makeBaseUrl = makeBaseUrl;

function Client(client) {
  this.client = client || null;
}

Client.prototype.stat = function(bucket, key, onret) {
	//获取转码后的bucket与key
  var encodedEntryUri = getEncodedEntryUri(bucket, key);
  var uri = conf.RS_HOST + '/stat/' + encodedEntryUri;
  var digest = util.generateAccessToken(uri, null);

  rpc.postWithoutForm(uri, digest, onret);
}

Client.prototype.remove = function(bucket, key, onret) {
  /*
   * func (this Client) Delete(bucket, key string) (err error)
   * */
  var encodedEntryUri = getEncodedEntryUri(bucket, key);
  var uri = conf.RS_HOST + '/delete/' + encodedEntryUri;
  var digest = util.generateAccessToken(uri, null);
  rpc.postWithoutForm(uri, digest, onret);
}

Client.prototype.move = function(bucketSrc, keySrc, bucketDest, keyDest, onret) {
  var encodedEntryURISrc = getEncodedEntryUri(bucketSrc, keySrc);
  var encodedEntryURIDest = getEncodedEntryUri(bucketDest, keyDest);
  var uri = conf.RS_HOST + '/move/' + encodedEntryURISrc + '/' + encodedEntryURIDest;
  var digest = util.generateAccessToken(uri, null);
  rpc.postWithoutForm(uri, digest, onret);
}

Client.prototype.copy = function(bucketSrc, keySrc, bucketDest, keyDest, onret) {
  var encodedEntryURISrc = getEncodedEntryUri(bucketSrc, keySrc);
  var encodedEntryURIDest = getEncodedEntryUri(bucketDest, keyDest);
  var uri = conf.RS_HOST + '/copy/' + encodedEntryURISrc + '/' + encodedEntryURIDest;
  var digest = util.generateAccessToken(uri, null);
  rpc.postWithoutForm(uri, digest, onret);
}

Client.prototype.fetch = function(url, bucket, key, onret) {
  var bucketUri = getEncodedEntryUri(bucket, key);
  var fetchUrl = util.urlsafeBase64Encode(url);
  var uri = 'http://iovip.qbox.me/fetch/' + fetchUrl + '/to/' + bucketUri;
  var digest = util.generateAccessToken(uri, null);
  rpc.postWithoutForm(uri, digest, onret);
}

function Entry(hash, fsize, putTime, mimeType, endUser) {
  this.hash = hash || null;
  this.fsize = fsize || null;
  this.putTime = putTime || null;
  this.mimeType = mimeType || null;
  this.endUser = endUser || null;
}

// ----- batch  -------

function EntryPath(bucket, key) {
  this.bucket = bucket || null;
  this.key = key || null;
}

EntryPath.prototype.encode = function() {
  return getEncodedEntryUri(this.bucket, this.key);
}

EntryPath.prototype.toStr = function(op) {
  return 'op=/' + op + '/' + getEncodedEntryUri(this.bucket, this.key) + '&';
}

function EntryPathPair(src, dest) {
  this.src = src || null;
  this.dest = dest || null;
}

EntryPathPair.prototype.toStr = function(op) {
  return 'op=/' + op + '/' + this.src.encode() + '/' + this.dest.encode() + '&';
}

function BatchItemRet(error, code) {
  this.error = error || null;
  this.code = code || null;
}

function BatchStatItemRet(data, error, code) {
  this.data = data;
  this.error = error;
  this.code = code;
}

Client.prototype.batchStat = function(entries, onret) {
  fileHandle('stat', entries, onret);
}

Client.prototype.batchDelete = function(entries, onret) {
  fileHandle('delete', entries, onret);
}

Client.prototype.batchMove = function(entries, onret) {
  fileHandle('move', entries, onret);
}

Client.prototype.batchCopy = function(entries, onret) {
  fileHandle('copy', entries, onret);
}

function fileHandle(op, entries, onret) {
  var body = '';
  for (var i in entries) {
    body += entries[i].toStr(op);
  }

  var uri = conf.RS_HOST + '/batch';
  var digest = util.generateAccessToken(uri, body);
  rpc.postWithForm(uri, body, digest, onret);
}

function getEncodedEntryUri(bucket, key) {
  return util.urlsafeBase64Encode(bucket + ':' + key);
}

// ----- token --------
// @gist PutPolicy
function PutPolicy(putPolicyObj,type,uploadType,platform,version,audioOrMedia) {
  if (typeof putPolicyObj !== 'object') {
    return false;
  }
  this.scope = putPolicyObj.scope || null;
  this.expires =3600;
  this.insertOnly = putPolicyObj.insertOnly || null;

  this.saveKey = putPolicyObj.saveKey || null;
  this.endUser = putPolicyObj.endUser || null;

  this.returnUrl = putPolicyObj.returnUrl || null;
  this.returnBody = putPolicyObj.returnBody || null;

//  this.callbackUrl = putPolicyObj.callbackUrl || null;
//  this.callbackHost = putPolicyObj.callbackHost || null;
//  this.callbackBody = putPolicyObj.callbackBody || null;

  
  this.callbackUrl="";
  if(type==1){
	  this.callbackUrl="http://tribe.aladada.com/qiniuUploadSuccess";
	  uploadType=0;
  }else if(type==2){
	  if(platform=="ios"){
		  this.callbackUrl="http://tribe.aladada.com/qiniuUploadOthersSuccess";
	  }else{
		  if(version!=null&&version!=""&&version!=undefined){
			  version=parseInt(version);
			  //大于本版本号才触发回调逻辑
			  if(version>=1109071519){
				  this.callbackUrl="http://tribe.aladada.com/qiniuUploadOthersSuccess";
			  }
		  }
	  }
  }else if(type==4 && audioOrMedia!="3"){
      // this.callbackUrl="http://tribe.aladada.com/qiniuCirclePicUpload";
      this.callbackUrl="http://stg-tribe.leanapp.cn/qiniuCirclePicUpload";
      uploadType=0;

  }else if(type==5){
      // this.callbackUrl="http://tribe.aladada.com/qiniuCircleCoverPicUpload";
      this.callbackUrl="http://stg-tribe.leanapp.cn/qiniuCircleCoverPicUpload";
      //uploadType=0;

  }else{
      
  }
//this.callbackHost = "tribe.avosapps.com";
  if(uploadType==undefined)
	  uploadType=-1;
  this.callbackBody = '{"uploadType":'+uploadType+',"key": $(key),"mimeType": $(mimeType),"ext": $(ext),"name": $(fname),"size": $(fsize),"hash": $(etag),"avinfo": $(avinfo),"imageInfo":$(imageInfo)}';
  this.callbackBodyType="application/json";
  this.persistentOps=null;
  this.persistentNotifyUrl=null;
  this.persistentPipeline = null;
  var extend = putPolicyObj.scope.substring(putPolicyObj.scope.lastIndexOf(".") + 1);
  if(extend!=null)
	  extend=extend.toLowerCase();
  extend=extend.replace(/\s/g, "");
  //上传图片
  if(picType.indexOf(extend)!=-1){
  }
  //上传视频
  else  if(vedioType.indexOf(extend)!=-1&&audioOrMedia=="3"){
	  //视频预处理

      console.log("平台："+platform);

	  if(platform=="ios"){
		  this.persistentOps="avthumb/mp4/vb/640k;vframe/jpg/offset/0.001/w/400/h/440;avthumb/m3u8/segtime/5/preset/video_640k/rotate/90";
	  }else{
		  if(version>1109101019){
			  this.persistentOps="avthumb/mp4/vb/640k;vframe/jpg/offset/0.001/w/400/h/440;avthumb/m3u8/segtime/5/preset/video_640k";
		  }else{
			  this.persistentOps="avthumb/mp4/vb/640k/rotate/90;vframe/jpg/offset/0.001/w/400/h/440/rotate/90;avthumb/m3u8/segtime/5/preset/video_640k/rotate/90";
		  }
		  
	  }
      if(type==4){
          this.persistentNotifyUrl="http://stg-tribe.leanapp.cn/qiniuCirclePicUpload";

      }else{
	  this.persistentNotifyUrl="http://tribe.aladada.com/qiniuPersistentMediaSuccess";
      }
	  this.persistentPipeline = "duilie1";
  //上传音频
  } else  if(audioType.indexOf(extend)!=-1 || type==-11){
	  //转为mp3并用audioMp3队列进行预处理
	  this.persistentOps="avthumb/mp3/ab/256k;avthumb/m3u8/segtime/15";
	  this.persistentNotifyUrl="http://tribe.aladada.com/qiniuPersistentAudioSuccess";
	  this.persistentPipeline = "duilie1";


  }else{
  }
  this.fsizeLimit = putPolicyObj.fsizeLimit || null;

  this.detectMime = putPolicyObj.detectMime || null;

  this.mimeLimit = putPolicyObj.mimeLimit || null;
}
// @endgist
exports.pfopQrCode=pfopQrCode;
function pfopQrCode(user,callback){
	 var mac = new Mac(conf.ACCESS_KEY, conf.SECRET_KEY);
	 var saved_bucket = 'family';
	 var saved_key = user.id+"_"+new Date().getTime()+".png";
	 saveas_key = util.urlsafeBase64Encode(saved_bucket+':'+saved_key);
	 // ------------------图片缩放-------------------
	 var fops1 =common.getQrCodeFormat(user);
	 var fops2 = fops1+'|saveas/'+saveas_key;
	 var bucket = 'family';
    if(!user.get("qrCodeOldSource")){
        return callback("qrCodeOldSource为空",null);
    }
	 var key = user.get("qrCodeOldSource")._name;
	 //根据处理需求选择不同的fop处理参数
	 var fops = fops2;
	 var pipleline = 'duilie1';
	 var opts = {
	     pipeline: pipleline,
	     notifyURL:"http://tribe.aladada.com/persistentNotifyUrl"
	 };
	 var PFOP = fop.pfop(bucket, key, fops, opts, function(err, ret) {
	       if(!err) {
	         // 上传成功， 处理返回值
	    	   return callback(null,ret.persistentId);
	       } else {
	         // 上传失败， 处理返回代码
	    	   return callback(err,null);
	       }
	   });
}
PutPolicy.prototype.token = function(mac) {
  if (mac == null) {
    mac = new Mac(conf.ACCESS_KEY, conf.SECRET_KEY);
  }
  var flags = this.getFlags();
  var encodedFlags = util.urlsafeBase64Encode(JSON.stringify(flags));
  var encoded = util.hmacSha1(encodedFlags, mac.secretKey);
  var encodedSign = util.base64ToUrlSafe(encoded);
  var uploadToken = mac.accessKey + ':' + encodedSign + ':' + encodedFlags;
  return uploadToken;
}

PutPolicy.prototype.getFlags = function() {
  var flags = {};
  var attrs = ['scope', 'insertOnly', 'saveKey', 'endUser', 'returnUrl', 'returnBody', 'callbackUrl', 'callbackHost', 'callbackBody', 'callbackBodyType', 'callbackFetchKey', 'persistentOps', 'persistentNotifyUrl', 'persistentPipeline', 'fsizeLimit', 'detectMime', 'mimeLimit'];
  for (var i = attrs.length - 1; i >= 0; i--) {
    if (this[attrs[i]] !== null) {
      flags[attrs[i]] = this[attrs[i]];
    }
  }
  flags['deadline'] = this.expires + Math.floor(Date.now() / 1000);
  return flags;
}

function GetPolicy(expires) {
  this.expires = expires || 3600;
}

GetPolicy.prototype.makeRequest = function(baseUrl, mac) {
  if (!mac) {
    mac = new Mac(conf.ACCESS_KEY, conf.SECRET_KEY);
  }

  var deadline = this.expires + Math.floor(Date.now() / 1000);

  if (baseUrl.indexOf('?') >= 0) {
    baseUrl += '&e=';
  } else {
    baseUrl += '?e=';
  }
  baseUrl += deadline;

  var signature = util.hmacSha1(baseUrl, mac.secretKey);
  var encodedSign = util.base64ToUrlSafe(signature);
  var downloadToken = mac.accessKey + ':' + encodedSign;

  return baseUrl + '&token=' + downloadToken;
}
// query like '-thumbnail', '?imageMogr2/thumbnail/960x' and so on
function makeBaseUrl(domain, key, query) {
  key = new Buffer(key);
  return 'http://' + domain + '/' + querystring.escape(key) + (query || '');
}